<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="本片文章主要讲述网络的基本概念。将多个节点通过特定的介质联系起来的一种关系。以计算设备作为节点，通信线路作为介质的网络。">
<meta name="keywords" content="Python,网络编程">
<meta property="og:type" content="article">
<meta property="og:title" content="网络编程基础篇">
<meta property="og:url" content="https://rencheng.cc/2019/07/14/python/网络编程01/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="本片文章主要讲述网络的基本概念。将多个节点通过特定的介质联系起来的一种关系。以计算设备作为节点，通信线路作为介质的网络。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-07-14T02:06:54.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="网络编程基础篇">
<meta name="twitter:description" content="本片文章主要讲述网络的基本概念。将多个节点通过特定的介质联系起来的一种关系。以计算设备作为节点，通信线路作为介质的网络。">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/07/14/python/网络编程01/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>网络编程基础篇 | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/07/14/python/网络编程01/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">网络编程基础篇

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-07-14 10:06:54" itemprop="dateCreated datePublished" datetime="2019-07-14T10:06:54+08:00">2019-07-14</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">2.6k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本片文章主要讲述网络的基本概念。<br>将多个节点通过特定的介质联系起来的一种关系。<br>以计算设备作为节点，通信线路作为介质的网络。</p>
<a id="more"></a>
<h2 id="网络的概念"><a href="#网络的概念" class="headerlink" title="网络的概念"></a>网络的概念</h2><ul>
<li>什么是网络：将多个节点通过特定的介质联系起来的一种关系<br>  例如：铁路网、交通网、人际关系网</li>
<li>计算机网络：以计算设备作为节点，通信线路作为介质的网络</li>
<li>英特网：把许多网络连到一起的网络</li>
<li>网络起源于美苏冷战，最初是美国国防部高级研究计划局的一个项目，后来转为民用</li>
</ul>
<h2 id="网络功能"><a href="#网络功能" class="headerlink" title="网络功能"></a>网络功能</h2><ul>
<li>数据与信息的传输</li>
<li>实现资源共享</li>
<li>打破时空限制，优化资源配置</li>
</ul>
<h2 id="网络分类"><a href="#网络分类" class="headerlink" title="网络分类"></a>网络分类</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">局域网、城域网、广域网</span><br></pre></td></tr></table></figure>
<h2 id="网络性能衡量指标"><a href="#网络性能衡量指标" class="headerlink" title="网络性能衡量指标"></a>网络性能衡量指标</h2><ul>
<li>带宽：通信信道支持的最高数据频率(Mb/s, kb/s, Gb/s)</li>
<li>传输速率：每秒传输多少个bit数据</li>
<li>吞吐量：单位时间内通过某个网络的数据量</li>
<li>时延：<ul>
<li>传输时延：发送数据时候，到完成发送</li>
<li>传播时延：电磁波、电信号传输需花费的时间</li>
<li>处理时延：网络数据交换节点存储、转发所必需的处理时间</li>
<li>排队时延：网络节点队列分组、排队所经历的时间</li>
</ul>
</li>
</ul>
<h2 id="常用概念"><a href="#常用概念" class="headerlink" title="常用概念"></a>常用概念</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">客户端：请求服务的一方</span><br><span class="line">服务器：提供服务的一方</span><br><span class="line">通信：数据传输过程</span><br><span class="line">协议：数据组织、编码、传输、校验、解码的规则</span><br></pre></td></tr></table></figure>
<h2 id="网络通信要解决的几个问题"><a href="#网络通信要解决的几个问题" class="headerlink" title="网络通信要解决的几个问题"></a>网络通信要解决的几个问题</h2><div class="table-container">
<table>
<thead>
<tr>
<th>客户端</th>
<th>服务器</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>如何找到对方</strong>&lt;/br&gt;查阅地址(DNS)</td>
<td><strong>如何让对方联系自己</strong>&lt;/br&gt;公布自己的网络地址</td>
</tr>
<tr>
<td><strong>如何联系对方</strong>&lt;/br&gt;主动敲门(发起网络连接)</td>
<td><strong>如何让对方联系自己</strong>&lt;/br&gt;开门迎客(监听、接收连接)</td>
</tr>
<tr>
<td><strong>如何正确传输数据</strong>&lt;/br&gt;通信协议</td>
<td><strong>如何正确传输数据</strong>&lt;/br&gt;通信协议&lt;/br&gt;</td>
</tr>
<tr>
<td><strong>如何让对方理解自己的意思</strong>&lt;/br&gt;应用协议</td>
<td><strong>如何让对方理解自己的意思</strong>&lt;/br&gt;应用协议</td>
</tr>
<tr>
<td><strong>如何结束对话</strong>&lt;/br&gt;关闭连接</td>
<td><strong>如何结束对话</strong>&lt;/br&gt;释放资源</td>
</tr>
</tbody>
</table>
</div>
<h2 id="协议"><a href="#协议" class="headerlink" title="协议"></a>协议</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">生活中的协议：汽车转向灯、交通信号灯</span><br><span class="line">协议是一组规则，数据组织、发送、传输、解析的规则</span><br><span class="line">协议由第三方机构事先指定，或通信双方约定</span><br><span class="line">协议需要通信各方共同遵守，否则就无法完成正常通信</span><br></pre></td></tr></table></figure>
<h2 id="网络模型"><a href="#网络模型" class="headerlink" title="网络模型"></a>网络模型</h2><p>OSI/ISO七层模型 —&gt; 网络通信标准化流程<br>ISO(国际标准化组织)<br>OSI(开放系统互联模型)</p>
<h3 id="OSI七层模型如下"><a href="#OSI七层模型如下" class="headerlink" title="OSI七层模型如下"></a>OSI七层模型如下</h3><figure class="highlight ada"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">应用层 : 提供用户服务,具体功能有程序体现</span><br><span class="line">表示层 : 数据的压缩优化和加密</span><br><span class="line">会话层 : 建立应用连接,选择合适的传输服务</span><br><span class="line">传输层 : 提供传输服务,进行流量控制</span><br><span class="line">网络层 : 路由选择,网络互连</span><br><span class="line">链路层 : 进行数据交换,控制具体消息收发,链路连接</span><br><span class="line">物理层 : 提供物理硬件传输,网卡,接口设置,传输介质</span><br></pre></td></tr></table></figure>
<h3 id="OSI七层模型优势"><a href="#OSI七层模型优势" class="headerlink" title="OSI七层模型优势:"></a>OSI七层模型优势:</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">建立了统一的网络工作流程 </span><br><span class="line">每个层次功能清晰,各司其职</span><br><span class="line">降低了耦合度,方便了开发流程</span><br></pre></td></tr></table></figure>
<h4 id="分层原则"><a href="#分层原则" class="headerlink" title="分层原则:"></a>分层原则:</h4><figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">高内聚: 模块功能尽可能单一,不要相互掺杂</span></span><br><span class="line"><span class="section">低耦合: 模块之间的关联影响尽可能少</span></span><br></pre></td></tr></table></figure>
<h3 id="四层模型-TCP-IP模型"><a href="#四层模型-TCP-IP模型" class="headerlink" title="四层模型 (TCP/IP模型)"></a>四层模型 (TCP/IP模型)</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">应用层   传输层  网络层  物理链路层</span><br></pre></td></tr></table></figure>
<blockquote>
<p>将应用层,表示层,会话层统一为应用层,便于开发实践</p>
</blockquote>
<h3 id="五层模型"><a href="#五层模型" class="headerlink" title="五层模型"></a>五层模型</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">应用层   传输层  网络层  链路层  物理层</span><br></pre></td></tr></table></figure>
<h2 id="数据的传输流程"><a href="#数据的传输流程" class="headerlink" title="数据的传输流程"></a>数据的传输流程</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">发送端由应用层逐层根据协议添加首部信息,最终在物理层实现发送</span><br><span class="line">发送的消息经过中间多个节点转发到达目标主机</span><br><span class="line">目标主机根据协议逐层解析首部,最终到达应用层获取数据</span><br></pre></td></tr></table></figure>
<h3 id="消息发送的流程"><a href="#消息发送的流程" class="headerlink" title="消息发送的流程"></a>消息发送的流程</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">封装：每个层次接收上层传递的数据，加入本层的控制信息，传递给下一层</span><br><span class="line">解封：每个层次接收下层传来的数据，读取并去掉控制信息，将数据送给上一层处理</span><br></pre></td></tr></table></figure>
<h3 id="数据包如何寻找路径"><a href="#数据包如何寻找路径" class="headerlink" title="数据包如何寻找路径"></a>数据包如何寻找路径</h3><figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">网络节点分配一个<span class="built_in">IP</span>地址（全世界独一无二的）</span><br><span class="line">数据包中，包含了数据的源地址、目标地址</span><br><span class="line">根据路由表中记录的路径信息，将数据投递给下一站，循环直至数据送达对方</span><br></pre></td></tr></table></figure>
<h2 id="网络地址表示方式"><a href="#网络地址表示方式" class="headerlink" title="网络地址表示方式"></a>网络地址表示方式</h2><p><strong>网络主机</strong>:  在网络中标识一台主机的标志<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">本地使用 : <span class="string">'localhost'</span> </span><br><span class="line">		 <span class="string">'127.0.0.1'</span></span><br><span class="line"></span><br><span class="line">网络使用 : <span class="string">'192.168.56.131'</span></span><br><span class="line">		 <span class="string">'0.0.0.0'</span></span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>ifconfig : 查看本地网络信息 (Unix, Linux)<br>ipconfig : 查看本地网络信息 (Windows) </p>
</blockquote>
<p><strong>IP地址</strong> : 在网络上查找一台主机的网络位置<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">IPv4</span> : 点分十进制 192<span class="selector-class">.168</span><span class="selector-class">.1</span><span class="selector-class">.2</span>   每部分取值<span class="selector-pseudo">:0--255</span></span><br><span class="line"></span><br><span class="line"><span class="selector-tag">IPv6</span> : 扩充地址的范围</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">ping</span> <span class="selector-attr">[ip]</span> : 网络连接测试</span><br><span class="line"></span><br><span class="line">特殊<span class="selector-tag">IP</span></span><br><span class="line">   127<span class="selector-class">.0</span><span class="selector-class">.0</span><span class="selector-class">.1</span>  本机测试<span class="selector-tag">IP</span></span><br><span class="line">   0<span class="selector-class">.0</span><span class="selector-class">.0</span><span class="selector-class">.0</span>  本机自动获取能够使用的网卡<span class="selector-tag">IP</span></span><br><span class="line">   192<span class="selector-class">.168</span><span class="selector-class">.1</span><span class="selector-class">.0</span>  表达一个网段</span><br><span class="line">   192<span class="selector-class">.168</span><span class="selector-class">.1</span><span class="selector-class">.1</span>  表示网关地址</span><br><span class="line">   192<span class="selector-class">.168</span><span class="selector-class">.1</span><span class="selector-class">.255</span>  广播地址</span><br></pre></td></tr></table></figure></p>
<p><strong>域名</strong> : 网络服务器的别名<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">方便记忆,表达一定的含义</span><br></pre></td></tr></table></figure></p>
<p><strong>端口号</strong> port<br><figure class="highlight tap"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">端口号是网络地址的一部分,用于区分主机上不同的网络应用</span><br><span class="line"></span><br><span class="line">在一个系统中应用监听的端口不重复</span><br><span class="line"></span><br><span class="line">取值范围:</span><br><span class="line">       <span class="number"> 1 </span>-- 65535</span><br><span class="line">       <span class="number"> 1 </span>--<span class="number"> 255 </span> 一些众所周知的公共程序端口</span><br><span class="line">       <span class="number"> 256 </span>--<span class="number"> 1023 </span> 系统应用端口</span><br><span class="line">       <span class="number"> 1024 </span>--<span class="number"> 65535 </span> 自用端口</span><br></pre></td></tr></table></figure></p>
<p><strong>网络字节序</strong> : 网络上数据传输的排列方式</p>
<h2 id="传输层"><a href="#传输层" class="headerlink" title="传输层"></a>传输层</h2><h3 id="面向连接的传输服务"><a href="#面向连接的传输服务" class="headerlink" title="面向连接的传输服务"></a>面向连接的传输服务</h3><p>基于TCP协议的数据传输</p>
<h4 id="传输特征"><a href="#传输特征" class="headerlink" title="传输特征 :"></a>传输特征 :</h4><p>提供可靠的数据传输,可靠性指的是传输。过程中无丢失,无失序,无差错,无重复</p>
<h4 id="实现手段"><a href="#实现手段" class="headerlink" title="实现手段"></a>实现手段</h4><p>在通信前需要建立通信连接，通信结束需要断开连接。</p>
<h4 id="连接过程-三次握手"><a href="#连接过程-三次握手" class="headerlink" title="连接过程 (三次握手)"></a>连接过程 (三次握手)</h4><figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="bullet">1. </span>客户端向服务端发起连接请求</span><br><span class="line"><span class="bullet">2. </span>服务端收到客户端请求报文(消息序列号),回复报文    消息表示可以连接</span><br><span class="line"><span class="bullet">3. </span>客户端收到服务端回复,再从发送报文最终建立连接</span><br></pre></td></tr></table></figure>
<h4 id="连接断开-四次挥手"><a href="#连接断开-四次挥手" class="headerlink" title="连接断开 (四次挥手)"></a>连接断开 (四次挥手)</h4><figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="bullet">1. </span>主动方发送报文提出断开连接</span><br><span class="line"><span class="bullet">2. </span>被动方接收到断开请求,立即返回消息表示开始准备    断开</span><br><span class="line"><span class="bullet">3. </span>被动方处理消息完毕,完成断开准备,再次发送报文    表示可以断开</span><br><span class="line"><span class="bullet">4. </span>主动方收到断开指令,发送报文最终确认断开</span><br></pre></td></tr></table></figure>
<h4 id="适用情况"><a href="#适用情况" class="headerlink" title="适用情况"></a>适用情况</h4><p>对数据传输有准确性的要求,传输文件较大;<br>需要确保传输可靠性。比如 : 网页获取,文件下载,邮件收发</p>
<h3 id="面向无连接的传输服务"><a href="#面向无连接的传输服务" class="headerlink" title="面向无连接的传输服务"></a>面向无连接的传输服务</h3><p>基于UDP协议的传输</p>
<h4 id="传输特征-1"><a href="#传输特征-1" class="headerlink" title="传输特征"></a>传输特征</h4><p>不保证传输的可靠性,数据传输不需要提前           建立连接</p>
<h4 id="适用情况-1"><a href="#适用情况-1" class="headerlink" title="适用情况"></a>适用情况</h4><p>网络情况较差,对传输可靠性要求不高。比如:网络视频,群聊,广播</p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/网络编程/" rel="tag"># 网络编程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/02/mysql/教程01/" rel="next" title="Mysql-教程01">
                <i class="fa fa-chevron-left"></i> Mysql-教程01
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/14/python/网络编程02/" rel="prev" title="Python-网络编程（一）">
                Python-网络编程（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#网络的概念"><span class="nav-number">1.</span> <span class="nav-text">网络的概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络功能"><span class="nav-number">2.</span> <span class="nav-text">网络功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络分类"><span class="nav-number">3.</span> <span class="nav-text">网络分类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络性能衡量指标"><span class="nav-number">4.</span> <span class="nav-text">网络性能衡量指标</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常用概念"><span class="nav-number">5.</span> <span class="nav-text">常用概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络通信要解决的几个问题"><span class="nav-number">6.</span> <span class="nav-text">网络通信要解决的几个问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#协议"><span class="nav-number">7.</span> <span class="nav-text">协议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络模型"><span class="nav-number">8.</span> <span class="nav-text">网络模型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#OSI七层模型如下"><span class="nav-number">8.1.</span> <span class="nav-text">OSI七层模型如下</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#OSI七层模型优势"><span class="nav-number">8.2.</span> <span class="nav-text">OSI七层模型优势:</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#分层原则"><span class="nav-number">8.2.1.</span> <span class="nav-text">分层原则:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四层模型-TCP-IP模型"><span class="nav-number">8.3.</span> <span class="nav-text">四层模型 (TCP/IP模型)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五层模型"><span class="nav-number">8.4.</span> <span class="nav-text">五层模型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据的传输流程"><span class="nav-number">9.</span> <span class="nav-text">数据的传输流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#消息发送的流程"><span class="nav-number">9.1.</span> <span class="nav-text">消息发送的流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据包如何寻找路径"><span class="nav-number">9.2.</span> <span class="nav-text">数据包如何寻找路径</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络地址表示方式"><span class="nav-number">10.</span> <span class="nav-text">网络地址表示方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#传输层"><span class="nav-number">11.</span> <span class="nav-text">传输层</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#面向连接的传输服务"><span class="nav-number">11.1.</span> <span class="nav-text">面向连接的传输服务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#传输特征"><span class="nav-number">11.1.1.</span> <span class="nav-text">传输特征 :</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#实现手段"><span class="nav-number">11.1.2.</span> <span class="nav-text">实现手段</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#连接过程-三次握手"><span class="nav-number">11.1.3.</span> <span class="nav-text">连接过程 (三次握手)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#连接断开-四次挥手"><span class="nav-number">11.1.4.</span> <span class="nav-text">连接断开 (四次挥手)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#适用情况"><span class="nav-number">11.1.5.</span> <span class="nav-text">适用情况</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#面向无连接的传输服务"><span class="nav-number">11.2.</span> <span class="nav-text">面向无连接的传输服务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#传输特征-1"><span class="nav-number">11.2.1.</span> <span class="nav-text">传输特征</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#适用情况-1"><span class="nav-number">11.2.2.</span> <span class="nav-text">适用情况</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
